<script setup lang="ts">
import { OrderState, orderStateList } from '@/services/constants'
import { deleteMemberOrderAPI, getMemberOrderAPI, putMemberOrderReceiptByIdAPI } from '@/services/order'
import { getPayMockAPI, getPayWxPayMiniPayAPI } from '@/services/pay'
import type { OrderItem, OrderListParams } from '@/types/order'
import { onMounted } from 'vue'
import { ref } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 使用props接收父组件传递的数据
const props = defineProps<{
    orderState: Number
}>()

// 定义请求列表参数
const queryParams: Required<OrderListParams> = {
    page: 1,
    pageSize: 5,
    orderState: props.orderState
}

// 存储订单列表数据
const orderList = ref<OrderItem[]>([])
// 分页结束标记
const finish = ref(false)
// 获取订单列表数据
const getMemberOrderData = async () => {
    // 若页码为最大后, 则不请求数据, 退出判断(性能优化)
    if (finish.value === true) {
        return uni.showToast({ icon: 'none', title: '没有更多订单了~' })
    }
    // 请求订单列表数据
    const res = await getMemberOrderAPI(queryParams)
    orderList.value.push(...res.result.items) // 数组追加
    // 分页条件-页码累加
    if (queryParams.page < res.result.pages) {
        queryParams.page++
    } else {
        finish.value = true
    }
}

// 组件加载时调用
onMounted(() => {
    getMemberOrderData()
})

// 订单支付按钮事件(请求支付接口并调用微信支付方法)
const onOrderPay = async (id: string) => {
    if (import.meta.env.DEV) {
        // 开发环境模拟支付
        await getPayMockAPI({ orderId: id })
    } else {
        // 正式环境微信支付
        // #ifdef MP-WEIXIN
        const res = await getPayWxPayMiniPayAPI({ orderId: id })
        wx.requestPayment(res.result)
        // #endif
    }
    // 此支付直接在当前页面更新并不跳转(支付成功则更新订单状态为待发货)
    const order = orderList.value.find(v => v.id === id)
    order!.orderState = OrderState.DaiFaHuo
    uni.showToast({ icon: 'success', title: '支付成功' })
}

// 控制下拉刷新状态
const isTriggered = ref(false)
// 下拉刷新时触发
const onRefresherrefresh = async () => {
    isTriggered.value = true  // 开始动画
    // 重置(分页为1, 列表数据清空, 分页结束为true), 后请求新数据
    queryParams.page = 1
    orderList.value = []
    finish.value = false
    await getMemberOrderData()
    isTriggered.value = false // 关闭动画
    uni.showToast({ icon: 'success', title: '刷新完成' })
}

// 滚动容器触底(触底发送请求)
const onScrolltolower = () => {
    getMemberOrderData()
}

// 删除订单按钮事件
const onOrderDelete = (id: string[]) => {
    // 二次确认(确认就请求删除订单, 并请求新列表数据)
    uni.showModal({
        content: '是否删除订单?',
        success: async (success) => {
            if (success.confirm) {
                await deleteMemberOrderAPI({ ids: id })
                // 重置(分页为1, 列表数据清空, 请求新数据)
                queryParams.page = 1
                orderList.value = []
                getMemberOrderData()
                uni.showToast({ icon: 'success', title: '删除成功' })
            }
        },
    })
}

// 确认收货按钮事件
const onOrderConfirm = (id: string) => {
    // 二次确认模态框
    uni.showModal({
        content: '为保障您的权益, 请收到货并确认无误后, 再确认收货',
        success: async (success) => {
            if (success.confirm) {
                // 发送确认收货接口后, 更新订单状态
                const res = await putMemberOrderReceiptByIdAPI(id)
                // 重置(分页为1, 列表数据清空, 请求新数据)
                queryParams.page = 1
                orderList.value = []
                getMemberOrderData()
                uni.showToast({ icon: 'success', title: '确认收货成功' })
            }
        }
    })
}
</script>

<template>
    <!-- 订单列表 -->
    <scroll-view scroll-y class="orders" refresher-enabled @refresherrefresh="onRefresherrefresh"
        :refresher-triggered="isTriggered" @scrolltolower="onScrolltolower">
        <view class="card" v-for="order in orderList" :key="order.id">
            <!-- 订单信息 -->
            <view class="status">
                <text class="date"> {{ order.createTime }} </text>
                <!-- 订单状态文字 -->
                <text> {{ orderStateList[order.orderState].text }} </text>
                <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
                <text class="icon-delete" v-if="order.orderState >= OrderState.DaiPingJia"
                    @tap="onOrderDelete([order.id])"></text>
            </view>
            <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
            <navigator v-for="item in order.skus" :key="item.id" class="goods"
                :url="`/pagesOrder/detail/detail?id=${order.id}`" hover-class="none">
                <view class="cover">
                    <image mode="aspectFit" :src="item.image">
                    </image>
                </view>
                <view class="meta">
                    <view class="name ellipsis"> {{ item.name }} </view>
                    <view class="type"> {{ item.attrsText }} </view>
                </view>
            </navigator>
            <!-- 支付信息 -->
            <view class="payment">
                <text class="quantity">共{{ order.totalNum }}件商品</text>
                <text>实付</text>
                <text class="amount"> <text class="symbol">¥</text> {{ order.payMoney }} </text>
            </view>
            <!-- 订单操作按钮 -->
            <view class="action">
                <!-- 待付款状态：显示去支付按钮 -->
                <template v-if="order.orderState === OrderState.DaiFuKuan">
                    <view @tap="onOrderPay(order.id)" class="button primary">去支付</view>
                </template>
                <template v-else>
                    <navigator class="button secondary" :url="`/pagesOrder/create/create?orderId=${order.id}`"
                        hover-class="none">
                        再次购买
                    </navigator>
                    <!-- 待收货状态: 展示确认收货 -->
                    <view v-if="order.orderState === OrderState.DaiShouHuo" @tap="onOrderConfirm(order.id)"
                        class="button primary">
                        确认收货</view>
                </template>
            </view>
        </view>
        <!-- 底部提示文字 -->
        <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            {{ finish ? '没有更多订单了~' : '正在加载...' }}
        </view>
    </scroll-view>
</template>

<style lang="scss">
// 订单列表
.orders {
    .card {
        min-height: 100rpx;
        padding: 20rpx;
        margin: 20rpx 20rpx 0;
        border-radius: 10rpx;
        background-color: #fff;

        &:last-child {
            padding-bottom: 40rpx;
        }
    }

    .status {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        color: #999;
        margin-bottom: 15rpx;

        .date {
            color: #666;
            flex: 1;
        }

        .primary {
            color: #ff9240;
        }

        .icon-delete {
            line-height: 1;
            margin-left: 10rpx;
            padding-left: 10rpx;
            border-left: 1rpx solid #e3e3e3;
        }
    }

    .goods {
        display: flex;
        margin-bottom: 20rpx;

        .cover {
            width: 170rpx;
            height: 170rpx;
            margin-right: 20rpx;
            border-radius: 10rpx;
            overflow: hidden;
            position: relative;
        }

        .quantity {
            position: absolute;
            bottom: 0;
            right: 0;
            line-height: 1;
            padding: 6rpx 4rpx 6rpx 8rpx;
            font-size: 24rpx;
            color: #fff;
            border-radius: 10rpx 0 0 0;
            background-color: rgba(0, 0, 0, 0.6);
        }

        .meta {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .name {
            height: 80rpx;
            font-size: 26rpx;
            color: #444;
        }

        .type {
            line-height: 1.8;
            padding: 0 15rpx;
            margin-top: 10rpx;
            font-size: 24rpx;
            align-self: flex-start;
            border-radius: 4rpx;
            color: #888;
            background-color: #f7f7f8;
        }

        .more {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22rpx;
            color: #333;
        }
    }

    .payment {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        line-height: 1;
        padding: 20rpx 0;
        text-align: right;
        color: #999;
        font-size: 28rpx;
        border-bottom: 1rpx solid #eee;

        .quantity {
            font-size: 24rpx;
            margin-right: 16rpx;
        }

        .amount {
            color: #444;
            margin-left: 6rpx;
        }

        .symbol {
            font-size: 20rpx;
        }
    }

    .action {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-top: 20rpx;

        .button {
            width: 180rpx;
            height: 60rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 20rpx;
            border-radius: 60rpx;
            border: 1rpx solid #ccc;
            font-size: 26rpx;
            color: #444;
        }

        .secondary {
            color: #27ba9b;
            border-color: #27ba9b;
        }

        .primary {
            color: #fff;
            background-color: #27ba9b;
        }
    }

    .loading-text {
        text-align: center;
        font-size: 28rpx;
        color: #666;
        padding: 20rpx 0;
    }
}
</style>